package com.hj.filter;

import cn.hutool.core.util.StrUtil;
import com.hj.config.security.token.PwdLoginToken;
import com.hj.domain.LoginUser;
import com.hj.domain.constant.HjConstant;
import com.hj.service.HjTokenService;
import lombok.extern.slf4j.Slf4j;

import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author < a href="huajian2018@aliyun.com">hj</ a>
 * @Description token 过滤器
 */
@Component
@Slf4j
public class TokenFilter extends OncePerRequestFilter {

    @Resource
    private HjTokenService hjTokenService;

    @Resource
    private UserDetailsService userDetailsServiceImpl;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        //获取token
        String token = getToken(request);
        if (StrUtil.isNotBlank(token)) {
            LoginUser loginUser = hjTokenService.get(token);
            log.info("TokenFilter  loginUser：" + loginUser);
            if (loginUser != null) {
                loginUser = checkLoginTime(loginUser, token);
                PwdLoginToken passwordAuthenticationToken = new PwdLoginToken(loginUser, null, null, loginUser.getAuthorities());
                log.info("UsernamePasswordAuthenticationToken:" + passwordAuthenticationToken);
                SecurityContextHolder.getContext().setAuthentication(passwordAuthenticationToken);
            }
        }

        filterChain.doFilter(request, response);

    }


    /**
     * @Description 根据request 参数获取head 获取请求
     **/
    public static String getToken(HttpServletRequest request) {
        String token = request.getParameter(HjConstant.TOKEN_KEY);
        if (StrUtil.isBlank(token)) {
            token = request.getHeader(HjConstant.TOKEN_KEY);
        }
        return token;
    }


    /**
     * @Description 过期时间与当前时间对比，临期十分钟内  自定刷新缓存
     **/
    private LoginUser checkLoginTime(LoginUser loginUser, String jwtToken) {
        long expireTime = loginUser.getExpireTime();
        long currentTime = System.currentTimeMillis();
        if (currentTime - expireTime >= HjConstant.MINUTES_10) {
            String token = loginUser.getToken();
            loginUser = (LoginUser) userDetailsServiceImpl.loadUserByUsername(loginUser.getMobile());
            loginUser.setToken(token);
            hjTokenService.refresh(loginUser);
        }
        return loginUser;
    }


}
